//
//  GlobalData.m
//  BTCoin
//
//  Created by Robin on 02/04/2018.
//  Copyright © 2018 Robin. All rights reserved.
//

#import "GlobalData.h"
#import "TradeService.h"

@implementation GlobalData
DEFINE_SINGLETON_FOR_CLASS(GlobalData)

- (void)requestTradeType:(CoinType)cType {
    [[TradeService sharedTradeService] tradeCenter:cType success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            BaseModel * userInfo = [[BaseModel alloc] initWithDictionary:responseObject error:nil];
            if (SuccessCode == userInfo.code) {
                NSDictionary * parDict = @{@"coinType":responseObject[@"coinType"],
                                           @"tradeType":responseObject[@"tradeType"]
                                           };
                [[TradeService sharedTradeService] tradeCoin:parDict success:^(id responseObject) {
                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        TradeCoinModel * userInfo = [[TradeCoinModel alloc] initWithDictionary:responseObject error:nil];
                        
                        if (SuccessCode == userInfo.code) {
                            if (cType == kCoinTypeCNY) {
                                [self saveCNYTradeCoinModel:userInfo];
                            } else if (cType == kCoinTypeBTC) {
                                [self saveBTCTradeCoinModel:userInfo];
                            }
                        }
                    }
                } fail:^(NSError *error) {
                }];
            }
        }
    } fail:^(NSError *error) {
    }];
}

- (void)saveCNYTradeCoinModel:(TradeCoinModel *)model {
    NSMutableArray * types = [NSMutableArray array];
    for (FTradeMappingModel * mapModel in model.ftrademappings) {
        FVirtualCoinTypeModel * vctypeModel = mapModel.fvirtualcointypeByFvirtualcointype2;
        NSString * shortName = [NSString stringWithFormat:@"%@",vctypeModel.fShortName];
        [types addObject:shortName];
    }
    
    self.tradeCNYTypeArray = types;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:UPDATECNYTRADETYPENOTIFICATION object:nil];
}

- (void)saveBTCTradeCoinModel:(TradeCoinModel *)model {
    NSMutableArray * types = [NSMutableArray array];
    for (FTradeMappingModel * mapModel in model.ftrademappings) {
        FVirtualCoinTypeModel * vctypeModel = mapModel.fvirtualcointypeByFvirtualcointype2;
        NSString * shortName = [NSString stringWithFormat:@"%@(BTC)",vctypeModel.fShortName];
        [types addObject:shortName];
    }
    
    self.tradeBTCTypeArray = types;
}

@end
